/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *    2012 year
 *    Author: Michael Khromov aka MikeDM (Mike D'Morto)
 *    E-Mail: mikedmorto@gmail.com
 */

#include "diastart.h"
#include "ui_diastart.h"
#include <QSettings>
#include <QPixmap>
#include <QPluginLoader>
#include <QMessageBox>
#include <QDebug>
#include "def.h"
#include "diasettings.h"
#include "iLogon.h"


DiaStart::DiaStart(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DiaStart)
{
    ui->setupUi(this);
    QSettings cfg(QSettings::IniFormat, QSettings::UserScope,
                            CORP_NAME, APP_NAME);
    this->ui->label->setPixmap(QPixmap(":/files/splash_logo.png"));
    connect(this->ui->btn_config,SIGNAL(clicked()),this,SLOT(slotSettings()));
    connect(this->ui->btn_logon,SIGNAL(clicked()),this,SLOT(slotLogon()));
    this->config = new QSettings(QSettings::IniFormat,QSettings::UserScope,CORP_NAME,APP_NAME);
    this->setWindowTitle(QString(APP_NAME)+" version "+QString(APP_VERSION));

}

DiaStart::~DiaStart()
{
    delete ui;
}

void DiaStart::slotSettings(){
    // читаем конфиг и отображаем его в диалоге настроек
    DiaSettings dia;
    dia.setLogonPlugin(this->config->value("logon","").toString());
    dia.setConnectHost(this->config->value("server","").toString());
    dia.setConnectPort(this->config->value("port",0).toInt());
    dia.setConnectDirect(this->config->value("use_direct_connection",true).toBool());
    if(dia.exec() == QDialog::Accepted){
        // вынимаем изменения, сохраняем их.
        this->config->setValue("logon",dia.getLogonPlugin());
        this->config->setValue("server",dia.getConnectHost());
        this->config->setValue("port",dia.getConnectPort());
        this->config->setValue("user_direct_connection",dia.getConnectDirect());
    }
}

void DiaStart::slotLogon(){
    // вызываем logon плагин прописанный в конфиге
    iLogon * logon;
    QPluginLoader loader;
    loader.setFileName(QString(PLUGIN_DIR)+QString(PLUGIN_PREFIX)+this->config->value("logon","").toString().split(",").at(0)
                       +QString(PLUGIN_SUFFIX));
    if(!loader.load()){
        // беда печаль, загрузка либы не удалась. ругаемся.
        QMessageBox::critical(this,tr("Error"),tr("Failure load logon plugin\n%1")
                              .arg(QString(PLUGIN_DIR)+QString(PLUGIN_PREFIX)+this->config->value("logon","").toString().split(",").at(0)
                                   +QString(PLUGIN_SUFFIX)),QMessageBox::Ok);
        return;
    }
    // инициализируем плагин входа
    logon = qobject_cast<iLogon*>(loader.instance());
    if(!logon->init(this->config->value("logon","").toString())){
        QMessageBox::critical(this,tr("Error"),tr("Failure init logon plugin\n%1")
                              .arg(this->config->value("logon","").toString().split(",").at(0)));
        return;
    }
    //  запускаем его главный диалог
    if(logon->exec() == QDialog::Accepted){
        // диалог отработал нормально - запускаем волшебную инициализацию плагинов и прочую ерунду.
    }else{
        // диалог отработал ненормально - кажем себя снова.
    }

}
